package logic.handler.face.impl;

import io.http.HTTPHandler;
import io.json.JsonReader;
import io.json.JsonWritter;
import logic.handler.face.inter.WeatherHandlerInter;
import model.CityBean;
import model.PmBean;

import javax.servlet.http.HttpServletResponse;

/**
 * 天气查询的Handler
 * Created by jcala on 2016/3/15.
 */
public class WeatherHandler implements WeatherHandlerInter {
    private CityBean city;
    private HttpServletResponse response;
    public WeatherHandler(CityBean city,HttpServletResponse response) {
        this();
        this.response=response;
        this.city = city;
    }

    private WeatherHandler() {
    }
    @Override
    public PmBean getWeather() {
        PmBean pm= null;
        try {
            pm = JsonReader.readPm(HTTPHandler.sendGet(city.getCity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pm;
    }

    /**
     * 1 从HTTP得到的json数据解析为包含城市名字的CityBean
     * 2 传入CityBean到HTTPHandler的sendGet方法得到pm2.5值
     * 3 将pm2.5值和状态码封装为PmBean
     * 4 将PmBean转换为json字符串并返回给客户端
     */
    @Override
    public void handle() {
        PmBean bean=getWeather();
        HTTPHandler.sendMsgToHTTP(response, JsonWritter.WriteToPm25(bean));
    }
}
